package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.model.PaasFormDataEsModel;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.pojo.dto.DeleteDTO;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.field.SaasParticularAttributePoJo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.wrap.EnableApiCallBack;
import com.xbongbong.paas.util.DataUtil;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.ApiCallBackEnum;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.domain.dao.CustomerCommunicateDao;
import com.xbongbong.saas.domain.entity.ext.CustomerCommunicateEntityExt;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CustomerCommunicateEnum;
import com.xbongbong.saas.enums.business.DistributorCommunicateEnum;
import com.xbongbong.saas.help.ShowFormatHelp;
import com.xbongbong.saas.model.CustomerCommunicateModel;
import com.xbongbong.saas.model.CustomerCommunicateSubDataModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.util.StandardizeDataUtil;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @author long.rao
 * @version v1.0
 * @date 2019/1/24 21:17
 * @since v1.0
 */
@Service("customerCommunicateModel")
public class CustomerCommunicateModelImpl implements CustomerCommunicateModel {

    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private CustomerCommunicateDao customerCommunicateDao;
    @Resource
    private PaasFormDataEsModel paasFormDataEsModel;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private CustomerCommunicateSubDataModel customerCommunicateSubDataModel;
    @Resource
    private ShowFormatHelp showFormatHelp;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.CUSTOMER_COMMUNICATE, operateTypeEnum = OperateTypeEnum.NEW)
    public Integer insert(CustomerCommunicateEntityExt entity) throws XbbException {
        //TODO  先进行数据库的插入动作
        long now = DateUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);
        paasFormSubDataModel.transferSubForm(entity,IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer insert = customerCommunicateDao.insert(entity);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(entity, IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE);
        paasEsModel.insert(insertDTO);
        paasFormSubDataModel.insertSubFormData(entity, IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE_SUB);
        return insert;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.CUSTOMER_COMMUNICATE, operateTypeEnum = OperateTypeEnum.NEW, isBatch = true)
    public List<CustomerCommunicateEntityExt> insertBatch(List<CustomerCommunicateEntityExt> customerCommunicateList) throws XbbException {
        for (CustomerCommunicateEntityExt entityExt : customerCommunicateList) {
            paasFormSubDataModel.transferSubForm(entityExt, IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE_SUB);
        }
        StandardizeDataUtil.standardize4EntityList(customerCommunicateList);
        customerCommunicateDao.insertBatch(customerCommunicateList);
        //ES数据插入
        List<InsertDTO> insertList = new ArrayList<>();
        for (CustomerCommunicateEntityExt item : customerCommunicateList) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setWaitUntil(WriteRequest.RefreshPolicy.NONE);
            insertDTO.setEsId(item.getCorpid() + "_" + item.getId());
            item.setDataId(item.getId());
            insertDTO.setSource(BeanUtil.convertBean2Map(item, true, true));
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE);
            insertList.add(insertDTO);
        }
        // 批量不等待
        paasEsModel.insertBatch(insertList, WriteRequest.RefreshPolicy.NONE);
        paasFormSubDataModel.insertBatchSubFormData(customerCommunicateList, IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE_SUB);
        return customerCommunicateList;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.CUSTOMER_COMMUNICATE, operateTypeEnum = OperateTypeEnum.EDIT)
    public Integer update(CustomerCommunicateEntityExt entity) throws XbbException {
        long now = DateUtil.getInt();
        entity.setUpdateTime(now);
        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer success = customerCommunicateDao.update(entity);
        Integer updateSub = paasFormSubDataModel.updateSubFormData(entity, IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE_SUB);
        if (Objects.equals(1, success) || Objects.equals(1, updateSub)) {
            // 更新时间
            success = customerCommunicateDao.updateTime(now + 1, entity.getId(), entity.getCorpid());
            InsertDTO insertDTO = paasEsModel.getSaveDTO(entity, IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE);
            paasEsModel.update(insertDTO);

        }
        if (Objects.nonNull(entity.getSubFormData()) && !entity.getSubFormData().isEmpty()) {
            entity.getData().putAll(entity.getSubFormData());
        }
        return success;
    }

    @Override
    public List<CustomerCommunicateEntityExt> findEntitys(Map<String, Object> param) {
        List<CustomerCommunicateEntityExt> entitys = customerCommunicateDao.findEntitys(param);
        Object corpid = param.get(ParameterConstant.CORPID);
        if (Objects.nonNull(corpid)) {
            paasFormSubDataModel.findSubEntity(corpid.toString(), entitys, IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE_SUB);
        }
        return entitys;
    }

    @Override
    public List<CustomerCommunicateEntityExt> findNotAutGenEntitys(Map<String, Object> param) {
        List<CustomerCommunicateEntityExt> entitys = customerCommunicateDao.findNotAutGenEntitys(param);
        Object corpid = param.get(ParameterConstant.CORPID);
        if (Objects.nonNull(corpid)) {
            paasFormSubDataModel.findSubEntity(corpid.toString(), entitys, IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE_SUB);
        }
        return entitys;
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return customerCommunicateDao.getEntitysCount(param);
    }

    @Override
    public CustomerCommunicateEntityExt getByKey(Long key, String corpid) {
        CustomerCommunicateEntityExt entityExt = customerCommunicateDao.getByKey(key, corpid);
        paasFormSubDataModel.findSubEntity(corpid, Collections.singletonList(entityExt), IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE_SUB);
        return entityExt;
    }

    @Override
    public List<CustomerCommunicateEntityExt> getByIdIn(List<Long> idIn, String corpid){
        if (CollectionsUtil.isEmpty(idIn)) {
            return null;
        }
        return customerCommunicateDao.getByIdIn(idIn, corpid);
    }


    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.CUSTOMER_COMMUNICATE, operateTypeEnum = OperateTypeEnum.DELETE, isBatch = true)
    public Integer deleteBatch(List<Long> idIn, String corpid)  throws XbbException {
        Integer integer = customerCommunicateDao.deleteBatch(idIn, corpid);
        paasEsModel.deleteBatch(idIn, corpid, DelEnum.DELETE.getDel(), IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE);
        paasFormSubDataModel.deleteBatchByDataId(idIn, corpid, IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE_SUB, DelEnum.DELETE_SUBFORM);
        return integer;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.CUSTOMER_COMMUNICATE, operateTypeEnum = OperateTypeEnum.DELETE)
    public Integer deleteByKey(Long key,String corpid) throws XbbException{
        DeleteDTO deleteDTO = new DeleteDTO();
        deleteDTO.setEsId(corpid+"_"+key);
        deleteDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE);
        paasEsModel.delete(deleteDTO);
        Integer integer = customerCommunicateDao.deleteByKey(key, corpid);
        paasFormSubDataModel.deleteByDataId(key, corpid, IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE_SUB);
        return integer;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.CUSTOMER_COMMUNICATE, operateTypeEnum = OperateTypeEnum.EDIT, isBatch = true)
    public Integer updateBatch(List<UpdateDataEntity> updateDataList, String corpid) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateDataList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateDataList);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(updateDataList)) {
            StandardizeDataUtil.standardizeList(updateDataList);
            integer = customerCommunicateDao.updateBatch(updateDataList, corpid);
            paasEsModel.updateBatchMuchField(updateDataList, IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE);
        }
        // todo
        if (!subList.isEmpty()) {
            customerCommunicateSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.CUSTOMER_COMMUNICATE, operateTypeEnum = OperateTypeEnum.EDIT, isBatch = true)
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException{
        if (CollectionsUtil.isEmpty(updateList)) {
            return 0;
        }
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateList);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(updateList)) {
            StandardizeDataUtil.standardizeList(updateList);
            integer = customerCommunicateDao.updateBatch(updateList, corpid);
            paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE, refreshPolicy);
        }
        // todo
        if (!subList.isEmpty()) {
            customerCommunicateSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    /**
     * 数据还原
     * @param dataIdList
     * @param corpid
     * @param del
     * @throws XbbException
     */
    @Override
    public Integer restoreBatch(List<Long> dataIdList, String corpid, Integer del) throws XbbException {
        Integer count = customerCommunicateDao.restoreBatch(dataIdList, corpid, del);
        updateBatchDel(dataIdList, corpid, del);
        paasFormSubDataModel.restoreBatch(dataIdList, corpid, IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE_SUB);
        return count;
    }

    private void updateBatchDel(List<Long> dataIdList, String corpid, Integer del) throws XbbException{
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("del", del);
        map.put("updateTime",DateTimeUtil.getInt());
        paasFormDataEsModel.updateBatch(dataIdList, corpid, map, IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE);
    }

    @Override
    public List<CustomerCommunicateEntityExt> findEntitysWithoutSub(Map<String, Object> param) {
        return customerCommunicateDao.findEntitys(param);
    }

    @Override
    public List<CustomerCommunicateEntityExt> findNotAutGenEntitysWithoutSub(Map<String, Object> param) {
        return customerCommunicateDao.findNotAutGenEntitys(param);
    }

    @Override
    public void formatUpdateExplain(FormatExplainDTO formatExplainDTO) throws XbbException {
        List<FieldAttrEntity> explainList = formatExplainDTO.getExplainList();
        Integer businessType = formatExplainDTO.getResult().getInteger(CustomerCommunicateEnum.COMMUNICATE_BUSINESS_TYPE.getAttr());
        boolean isClue = false;
        if (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {
            // 当是线索的时候，需要做以下特殊处理，跟进业务处理成只有一个销售线索的下拉，而且解释字段去掉关联客户和关联联系人，因为线索和这两个业务没有特殊逻辑，所以不需要
            isClue = true;
        }

        Integer fromCopy = BasicConstant.ZERO;
        if(formatExplainDTO.getFromCopy() != null){
            // true: 复制1 false：编辑0
            fromCopy = formatExplainDTO.getFromCopy() ? BasicConstant.ONE : BasicConstant.ZERO;
        }
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            String attr = fieldAttrEntity.getAttr();
            if ((Objects.equals(attr, CustomerCommunicateEnum.COMMUNICATE_TIME.getAttr())
                    || Objects.equals(attr, CustomerCommunicateEnum.CUSTOMER_NAME.getAttr())) && Objects.equals(fromCopy, BasicConstant.ZERO)) {
                fieldAttrEntity.setEditable(0);
            } else if (Objects.equals(attr, CustomerCommunicateEnum.COMMUNICATE_BUSINESS.getAttr()) && isClue) {
                ItemPoJo itemPoJo = new ItemPoJo(XbbRefTypeEnum.CLUE.getName(), XbbRefTypeEnum.CLUE.getCode(), true);
                List<ItemPoJo> items = new ArrayList<>();
                items.add(itemPoJo);
                fieldAttrEntity.setItems(items);
                fieldAttrEntity.setSaasParticularAttributePoJo(new SaasParticularAttributePoJo());
            }
        }
        if (isClue) {
            List<String> attrs = CustomerCommunicateEnum.getCommunicateRemoveAttrs4Clue();
            explainList.removeIf(item -> attrs.contains(item.getAttr()));
        }
    }

    @Override
    public void formatData(SaasAnalysisDataDTO formDataUpdateGetDTO, JSONObject result) throws XbbException {
        showFormatHelp.formatLinkBusiness4Show(result, CustomerCommunicateEnum.CUSTOMER_NAME.getAttr(), CustomerCommunicateEnum.CUSTOMER_NAME_LINK_TEXT.getAttr(), CustomerCommunicateEnum.CUSTOMER_NAME.getFieldType());
        showFormatHelp.realTime4CommunicateContact(result, CustomerCommunicateEnum.CONTACT_ARRAY.getAttr(), CustomerCommunicateEnum.CONTACT_NAME_LINK_TEXT.getAttr(),CustomerCommunicateEnum.CONTACT_ARRAY.getFieldType(),formDataUpdateGetDTO.getCorpid());
        showFormatHelp.formatCommunicateBusiness4Show(result, CustomerCommunicateEnum.COMMUNICATE_BUSINESS.getAttr(), CustomerCommunicateEnum.COMMUNICATE_BUSINESS_TYPE.getAttr(), CustomerCommunicateEnum.COMMUNICATE_BUSINESS_LINK_TEXT.getAttr());
        showFormatHelp.formatLinkBusiness4Show(result, CustomerCommunicateEnum.FINISH_COMMUNICATE_PLAN_ID.getAttr(), CustomerCommunicateEnum.FINISH_COMMUNICATE_PLAN_LINK_TEXT.getAttr(),CustomerCommunicateEnum.FINISH_COMMUNICATE_PLAN_ID.getFieldType());
    }

    @Override
    public void formatUpdateExplainForDistributor(FormatExplainDTO formatExplainDTO) throws XbbException {
        List<FieldAttrEntity> explainList = formatExplainDTO.getExplainList();
        Integer fromCopy = BasicConstant.ZERO;
        if(formatExplainDTO.getFromCopy() != null){
            // true: 复制1 false：编辑0
            fromCopy = formatExplainDTO.getFromCopy() ? BasicConstant.ONE : BasicConstant.ZERO;
        }
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            String attr = fieldAttrEntity.getAttr();
            if ((Objects.equals(attr, DistributorCommunicateEnum.COMMUNICATE_TIME.getAttr())
                    || Objects.equals(attr, DistributorCommunicateEnum.DISTRIBUTOR_NAME.getAttr())) && Objects.equals(fromCopy, BasicConstant.ZERO)) {
                fieldAttrEntity.setEditable(0);
            }
        }
    }

    @Override
    public void formatDataForDistributor(SaasAnalysisDataDTO formDataUpdateGetDTO, JSONObject result) throws XbbException {
        showFormatHelp.formatLinkBusiness4Show(result, DistributorCommunicateEnum.DISTRIBUTOR_NAME.getAttr(), DistributorCommunicateEnum.DISTRIBUTOR_NAME_LINK_TEXT.getAttr(), DistributorCommunicateEnum.DISTRIBUTOR_NAME.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, DistributorCommunicateEnum.CONTACT_ARRAY.getAttr(), DistributorCommunicateEnum.CONTACT_NAME_LINK_TEXT.getAttr(),DistributorCommunicateEnum.CONTACT_ARRAY.getFieldType());
        showFormatHelp.formatCommunicateBusiness4Show(result, DistributorCommunicateEnum.COMMUNICATE_BUSINESS.getAttr(), DistributorCommunicateEnum.COMMUNICATE_BUSINESS_TYPE.getAttr(), DistributorCommunicateEnum.COMMUNICATE_BUSINESS_LINK_TEXT.getAttr());
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.CUSTOMER_COMMUNICATE, operateTypeEnum = OperateTypeEnum.NEW)
    public Integer insertByTime(CustomerCommunicateEntityExt entity) throws XbbException {
        //TODO  先进行数据库的插入动作
        paasFormSubDataModel.transferSubForm(entity,IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer insert = customerCommunicateDao.insert(entity);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(entity, IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE);
        paasEsModel.insert(insertDTO);
        paasFormSubDataModel.insertSubFormData(entity, IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE_SUB);
        return insert;
    }


    @Override
    public <T> List<T> getCustomerCommunicateListByLinkId(String corpid, Long linkId, CustomerCommunicateEnum customerCommunicateEnum, Class<T> clazz, String orderField, SortOrder sortOrder) throws XbbException {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery(CustomerCommunicateEnum.getEsAttr4Keyword(customerCommunicateEnum), linkId));
        boolQueryBuilder.filter(termQuery("del", 0));
        boolQueryBuilder.filter(termQuery(FieldTypeEnum.LOG_TYPE.getAlias(), 0));
        IndexTypeEnum indexTypeEnum = IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE;
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,indexTypeEnum.getType()));
        sourceBuilder.query(boolQueryBuilder);
        sourceBuilder.sort(new FieldSortBuilder(orderField).order(sortOrder));
        PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 0, PaasConstant.ES_MAX_PAGE_SIZE);
        SearchRequest searchRequest = new SearchRequest(indexTypeEnum.getIndex());
        searchRequest.source(sourceBuilder);
        XbbAggregatedPage<T> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, clazz);
        return esEntities.getContent();
    }

    @Override
    public <T> List<T> getCustomerCommunicateListByBoolQuery(String corpid, BoolQueryBuilder boolQueryBuilder, Class<T> clazz, String orderField, SortOrder sortOrder) throws XbbException {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));

        boolQueryBuilder.filter(termQuery("del", 0));
        boolQueryBuilder.filter(termQuery(FieldTypeEnum.LOG_TYPE.getAlias(), 0));
        IndexTypeEnum indexTypeEnum = IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE;
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,indexTypeEnum.getType()));
        sourceBuilder.sort(new FieldSortBuilder(orderField).order(sortOrder));
        sourceBuilder.query(boolQueryBuilder);
        SearchRequest searchRequest = new SearchRequest(indexTypeEnum.getIndex());
        searchRequest.source(sourceBuilder);
        PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 0, PaasConstant.ES_MAX_PAGE_SIZE);
        XbbAggregatedPage<T> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, clazz);
        return esEntities.getContent();
    }

    @Override
    public Long getMaxId() throws XbbException {
        return customerCommunicateDao.getMaxId();
    }

}
